/*
 * @description:
 * @author: steve.deng
 * @Date: 2020-08-06 10:48:04
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-09-16 00:04:33
 */

const file_os = require('fs')
const cp = require('child_process')
const util = require('util')
const exec = util.promisify(cp.exec)
const iconv = require('iconv-lite')
const chalk = require('chalk')
const glob = require('glob')
const os = require('os')
const path = require('path')
const ora = require('ora')

function format_time(value, type) {
  if (!value) return null
  let time
  if (value.constructor === Date) {
    time = value
  } else {
    time =
      value.toString().length > 10
        ? new Date(parseInt(value))
        : new Date(parseInt(value) * 1000)
  }
  let formatTime = type ? type : 'yyyy-MM-dd hh:mm:ss'
  let date = {
    'M+': time.getMonth() + 1,
    'd+': time.getDate(),
    'h+': time.getHours(),
    'm+': time.getMinutes(),
    's+': time.getSeconds(),
    'q+': Math.floor((time.getMonth() + 3) / 3),
    'S+': time.getMilliseconds(),
  }
  if (/(y+)/i.test(formatTime)) {
    formatTime = formatTime.replace(
      RegExp.$1,
      (time.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (let k in date) {
    if (new RegExp('(' + k + ')').test(formatTime)) {
      formatTime = formatTime.replace(
        RegExp.$1,
        RegExp.$1.length == 1
          ? date[k]
          : ('00' + date[k]).substr(('' + date[k]).length)
      )
    }
  }
  return formatTime
}

// 拷贝文本
function copyToClipboard(text, func) {
  const ostype = os.type()
  if (ostype == 'Darwin') {
    pbcopy(text)
    return
  }
  // CMD默认是GBK编码。而Node.js默认是UTF-8编码——这种编码差异，对中文而言，肯定会出问题的嘛。 所以text转为gbk
  text = iconv.encode(text, 'gbk')
  let resultfileName = 'result.txt'
  let command = `clip < ${resultfileName} `
  // 写入要粘贴的内容进result.txt
  file_os.writeFileSync(resultfileName, text, { encoding: 'utf8' })
  var cmdFileName = 'copy.bat'
  // 写入粘贴命令 clip < result.text 进copy.bat
  file_os.writeFileSync(cmdFileName, command, { encoding: 'utf8' })
  exec(cmdFileName, function (err, stdout, stderr) {
    if (err || stderr) return console.log(err, stdout, stderr)
    // 用nodejs删除文件
    file_os.unlinkSync(cmdFileName)
    file_os.unlinkSync(resultfileName)
    func(text, stdout)
  })
}

function pbcopy(data) {
  var proc = require('child_process').spawn('pbcopy')
  proc.stdin.write(data)
  proc.stdin.end()
}

//获取路径下所有文件的图片个数
function getImageFiles(imageFolder) {
  const arr = glob.sync(`${imageFolder}/**/*.?(jpg|png|jpeg|gif|tiff|bmp)`)
  return arr.length
}

const log = (message) => console.log(chalk.cyan(`${message}`))
const successLog = (message) => console.log(chalk.blue(`${message}`))
const errorLog = (error) => console.log(chalk.red(`${error}`))
const resolve = (...file) => path.resolve(process.cwd(), ...file)

function fsExistsSync(path) {
  try {
    // @ts-ignore
    fs.accessSync(path, fs.F_OK)
  } catch (e) {
    return false
  }
  return true
}

let spinner
function showLoading(option = {}) {
  spinner = ora(option.message || 'Loading').start()
}

function hideLoading(option = {}) {
  spinner.stop()
}

function formateTime(time) {
  const h = parseInt(time / 3600)
  const minute = parseInt((time / 60) % 60)
  const second = Math.ceil(time % 60)

  const hours = h < 10 ? '0' + h : h
  const formatSecond = second > 59 ? 59 : second
  return `${hours > 0 ? `${hours}:` : ''}${
    minute < 10 ? '0' + minute : minute
  }:${formatSecond < 10 ? '0' + formatSecond : formatSecond}`
}

function getHirtime() {
  var t1 = new Date().getTime()
  var t2 = t1
  var i = 0,
    count = 10000000,
    interval = 0
  t1 = process.uptime()
  for (i = 0; i < count; i++) {
    t2 = process.uptime()
    //interval = (t2 - t1);
  }
  interval = (t2 - t1).toFixed(2) + 'min'
  return interval
}

module.exports = {
  format_time,
  copyToClipboard,
  log,
  successLog,
  errorLog,
  resolve,
  getImageFiles,
  fsExistsSync,
  showLoading,
  hideLoading,
  getHirtime,
}
